    package com.example.controller;

    import com.example.data.entity.PreprocessedData;
    import com.example.data.entity.kg.KgEntity;
    import com.example.data.entity.kg.KgRelation;
    import com.example.data.mapper.KgRelationMapper;
    import com.example.data.mapper.PreprocessedDataMapper;
    import com.example.service.DataService;
    import com.example.service.RelationExtractService;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.annotations.ApiParam;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;

    import jakarta.annotation.Resource;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    /**
     * 秦朝史料控制器：提供HTTP接口触发爬取、清洗和知识图谱构建
     */
    @RestController
    @RequestMapping("/api/qin-history")
    @Api(tags = "秦朝史料处理接口", description = "用于爬取、清洗秦朝史料并构建知识图谱")
    public class HistoricalController {

        @Resource
        private DataService DataService;

        @Resource
        private PreprocessedDataMapper preprocessedDataMapper;

        // 新增：关系抽取服务依赖
        @Resource
        private RelationExtractService relationExtractService;

        // 新增：关系表Mapper（用于查询关系结果）
        @Resource
        private KgRelationMapper kgRelationMapper;

        /**
         * 接口1：爬取秦朝史料并保存到原始数据表
         */
        @PostMapping("/crawl")
        @ApiOperation(value = "爬取秦朝史料", notes = "从 https://zhonghua.5000yan.com/qinchao/ 爬取所有章节数据")
        public ResponseEntity<Map<String, Object>> crawlQinData() {
            Map<String, Object> result = new HashMap<>();
            try {
                int count = DataService.crawlAndSaveQinData();
                result.put("success", true);
                result.put("message", "爬取成功");
                result.put("chapterCount", count);
                return ResponseEntity.ok(result);
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "爬取失败：" + e.getMessage());
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        }

        /**
         * 触发数据清洗程序
         */
        @PostMapping("/clean")
        @ApiOperation("清洗原始数据并入库")
        public ResponseEntity<Map<String, Object>> cleanRawData() {
            Map<String, Object> result = new HashMap<>();
            try {
                int cleanedCount = DataService.cleanData(); // 调用Service层的清洗方法
                result.put("success", true);
                result.put("message", "数据清洗完成");
                result.put("cleanedCount", cleanedCount); // 返回成功清洗的记录数
                return ResponseEntity.ok(result);
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "清洗失败：" + e.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }
        }

        @PostMapping("/preprocess")
        @ApiOperation("预处理清洗后的数据")
        public ResponseEntity<Map<String, Object>> preprocessData() {
            Map<String, Object> result = new HashMap<>();
            try {
                int count = DataService.preprocessCleanedData();
                result.put("success", true);
                result.put("message", "数据预处理完成");
                result.put("preprocessedCount", count);
                return ResponseEntity.ok(result);
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "预处理失败：" + e.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }
        }

        /**
         * 接口5：批量对未抽取的预处理数据进行实体抽取
         */
        @PostMapping("/extract/entity/batch")
        @ApiOperation(value = "批量实体抽取", notes = "对所有未抽取实体的预处理数据进行批量处理（默认每次处理20条）")
        public ResponseEntity<Map<String, Object>> extractEntityBatch(
                @ApiParam(value = "每次处理数量（默认20）", example = "20")
                @RequestParam(name = "batchSize", required = false, defaultValue = "20") Integer batchSize) {

            Map<String, Object> result = new HashMap<>();
            try {
                // 1. 查询未抽取实体的预处理数据
                List<PreprocessedData> unprocessedList = preprocessedDataMapper.selectUnExtractedEntities(batchSize);
                if (unprocessedList.isEmpty()) {
                    result.put("success", true);
                    result.put("message", "无未抽取实体的预处理数据");
                    return ResponseEntity.ok(result);
                }

                // 2. 批量处理
                int totalExtracted = 0;
                for (PreprocessedData preData : unprocessedList) {
                    totalExtracted += DataService.extractEntities(preData);
                    // 标记为已抽取（需在PreprocessedData表添加is_entity_extracted字段）
                    preprocessedDataMapper.markEntityExtracted(preData.getId());
                }

                result.put("success", true);
                result.put("message", "批量实体抽取完成");
                result.put("processedCount", unprocessedList.size());  // 处理的预处理数据量
                result.put("totalExtractedEntities", totalExtracted);  // 总抽取实体数
                return ResponseEntity.ok(result);
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "批量实体抽取失败：" + e.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }
        }

        /**
         * 接口6：批量关系抽取（核心）
         * 对未抽取关系的预处理数据进行批量处理，依赖已完成的实体抽取结果
         */
        @PostMapping("/extract/relation/batch")
        @ApiOperation(value = "批量关系抽取", notes = "对已完成实体抽取、但未抽取关系的预处理数据批量处理（默认每次20条）")
        public ResponseEntity<Map<String, Object>> extractRelationBatch(
                @ApiParam(value = "每次处理数量（默认20，建议不超过50）", example = "20")
                @RequestParam(name = "batchSize", required = false, defaultValue = "20") Integer batchSize) {

            Map<String, Object> result = new HashMap<>();
            try {
                // 调用RelationExtractService批量抽取关系（内部已处理数据查询、去重、入库）
                int totalExtractedRelations = relationExtractService.batchExtractRelations(batchSize);

                // 补充统计信息：查询未抽取关系的数据剩余量（给前端展示进度）
                List<PreprocessedData> remainingUnprocessed = preprocessedDataMapper.selectUnExtractedRelations(1);
                int remainingCount = remainingUnprocessed.size() > 0 ?
                        preprocessedDataMapper.selectUnExtractedRelations(Integer.MAX_VALUE).size() : 0;

                result.put("success", true);
                result.put("message", "批量关系抽取完成");
                result.put("batchSize", batchSize); // 本次处理批次大小
                result.put("totalExtractedRelations", totalExtractedRelations); // 本次抽取关系总数
                result.put("remainingUnprocessedCount", remainingCount); // 剩余未抽取关系的数据量
                return ResponseEntity.ok(result);

            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "批量关系抽取失败：" + e.getMessage());
                // 打印详细错误日志（便于后端排查）
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        }

        /**
         * 接口7：查询单条预处理数据的关系抽取结果（溯源用）
         * 根据预处理数据ID，查询该文本抽取的所有有效关系
         */
        @GetMapping("/extract/relation/result")
        @ApiOperation(value = "查询关系抽取结果", notes = "根据预处理数据ID，查询该数据对应的所有已抽取关系")
        public ResponseEntity<Map<String, Object>> getRelationResultByPreprocessedId(
                @ApiParam(value = "预处理数据ID（preprocessed_data表的id）", required = true, example = "1001")
                @RequestParam(name = "preprocessedId") Long preprocessedId) {

            Map<String, Object> result = new HashMap<>();
            try {
                // 1. 先校验预处理数据是否存在
                PreprocessedData preData = preprocessedDataMapper.selectById(preprocessedId); // 需在PreprocessedDataMapper新增selectById方法
                if (preData == null) {
                    result.put("success", false);
                    result.put("message", "预处理数据不存在，preprocessedId：" + preprocessedId);
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
                }

                // 2. 查询该预处理数据对应的所有有效关系
                List<KgRelation> relations = kgRelationMapper.selectByPreprocessedId(preprocessedId);

                result.put("success", true);
                result.put("message", "关系抽取结果查询成功");
                result.put("preprocessedDataInfo", Map.of( // 预处理数据基础信息（便于前端关联文本）
                        "preprocessedId", preprocessedId,
                        "cleanedId", preData.getCleanedId(),
                        "annotatedText", preData.getAnnotatedText().length() > 200 ?
                                preData.getAnnotatedText().substring(0, 200) + "..." : preData.getAnnotatedText()
                ));
                result.put("relationList", relations); // 该数据对应的所有关系列表
                result.put("relationCount", relations.size()); // 关系总数
                return ResponseEntity.ok(result);

            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "查询关系结果失败：" + e.getMessage());
                e.printStackTrace();
                return ResponseEntity.internalServerError().body(result);
            }
        }

        /**
         * 接口8：统计知识图谱关系总数（监控用）
         * 统计kg_relation表中所有有效关系的总数，用于展示图谱构建进度
         */
        @GetMapping("/graph/relation/total")
        @ApiOperation(value = "统计关系总数", notes = "查询kg_relation表中所有有效（is_valid=1）的关系总数")
        public ResponseEntity<Map<String, Object>> getTotalRelationCount() {
            Map<String, Object> result = new HashMap<>();
            try {
                // 需在KgRelationMapper新增统计有效关系总数的方法
                int totalValidRelations = kgRelationMapper.selectTotalValidCount();

                result.put("success", true);
                result.put("message", "关系总数统计成功");
                result.put("totalValidRelations", totalValidRelations); // 有效关系总数
                return ResponseEntity.ok(result);

            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "统计关系总数失败：" + e.getMessage());
                e.printStackTrace();
                return ResponseEntity.internalServerError().body(result);
            }
        }


    }
